/**
 * Created by Administrator on 2016/9/20 0020.
 *
 *
 */

var formhelper = function(form) {
    var formmy = { item: {} };
    var mainform = form;

    formhelper.prototype = {
            constructor: formhelper,
            subflag: function() {
                let flag = true;
                for (let i in this.item) {
                    flag = flag && this.item[i].subflag;
                }

                return flag;
            }, //subflag

            setbtn: function(butn) {
                this.btn = butn;
                let famm = this;
                this.btn.click(function () {
                    famm.submit();
                });
                return this;
            }, //setbtn

            submit: function() {
                if (this.btn.attr("type") == "button") {
                    let s = this.item,
                        flag = true,
                        jqtip, value, submit_list, sarr = mainform.serializeArray();


                    for (let fi in s) {
                        if (s[fi].ueditor != undefined) {
                            jqtip = "#" + s[fi].ueditor;
                        } else {
                            jqtip = "[name=" + fi + "]";
                        }

                        $(jqtip).next(".warnner").remove();
                        if (s[fi].type !== 'input') {

                            if (!submit_list) {
                                submit_list = {};
                                for (let i in sarr) {
                                    // console.log('####',sarr[i].name,sarr[i].value);
                                    submit_list[sarr[i].name] = sarr[i].value;
                                }
                            } // if(submit_list[fi])

                            value = submit_list[fi];
                        } else {
                            value = $("[name=" + fi + "]").val();
                        }

                        if ( //必填，而且不为空（0,"",undefined）
                            s[fi].ismust === true &&
                            (
                                value * 1 == 0 ||
                                value == "" ||
                                value == undefined
                            )
                        ) {
                            if (s[fi].ueditor != undefined && UE.getEditor(s[fi].ueditor).getContent() != "") {
                                s[fi].subflag = true;
                            } else {
                                // console.log(jqtip,$(jqtip));
                                $(jqtip + ":last").after("<span class='warnner' style='color:red;float:initial;'>" + s[fi].txt + "&nbsp;不能为空！</span>");
                                s[fi].subflag = false;
                            }
                        } else if (s[fi].ismust === true) {
                            s[fi].subflag = true;
                        }
                    }
                    if (this.subflag() == true) {
                        // console.log('subflag',this.item);
                        // return 0;
                        for (let fi in s) {
                            if (s[fi].ueditor != undefined) {
                                jqtip = "#" + s[fi].ueditor;
                            } else {
                                jqtip = "[name=" + fi + "]";
                            }

                            if (s[fi].type == 'checkbox') {
                                $(jqtip).attr('name', fi + '[]');
                            }
                        }

                        this.btn.attr("type", "submit");
                        this.btn.click(); //修复ueditor不能用submit提交，只能模拟click事件。
                    }
                }
                return this;
            }, //submit

            setmust: function(t) {
                if (arguments.length > 1) {
                    for (let i = 0; i < arguments.length; i++) {
                        if (this.item[arguments[i]] != undefined)
                            this.item[arguments[i]].ismust = true;
                        this.item[arguments[i]].subflag = false;
                    }
                } else if (arguments.length == 0) {
                    console.error("must be an argument");
                } else {
                    if (typeof t != "object") {
                        console.error("type error, must be like {name:['a','b','c']}");
                    } else if (t.name != undefined) {
                        for (let i = 0; i < t.name.length; i++) {
                            if (this.item[t.name[i]] != undefined) {
                                this.item[t.name[i]].ismust = true;
                                this.item[t.name[i]].subflag = false;
                            }
                        }
                    }
                } //end if

                return this;
            }, //setmust

            lessthan: function(t) {
                if (typeof t != "object") {
                    console.error("type error, must be like {name:100}");
                } else {
                    for (let i in t) {
                        if (this.item[i] != undefined) {
                            let that = this; //修复监听时jquery中的this覆盖原来的对象
                            mainform.find("[name=" + i + "]")
                                .after("<span class='ckless' style=''>最多" + t[i] + "个，已经输入<span class='cknumber'>0</span>个</span>")
                                .data("less", t[i])
                                .bind('input propertychange', function(item) {

                                    let name = $(this).attr("name");
                                    let num = $(this).val().length;
                                    let number = $(this).next(".ckless").find(".cknumber");
                                    number.html(num);
                                    if (num > $(this).data("less")) {
                                        number.css("color", "red");
                                        that.item[name].subflag = false;
                                    } else {
                                        number.css("color", "black");
                                        that.item[name].subflag = true;
                                    }
                                });
                        }
                    }
                }
                return this;
            }, //lessthan

            morethan: function(t) {
                if (typeof t != "object") {
                    console.error("type error, must be like {name:100}");
                } else {
                    for (let i in t) {
                        if (this.item[i] != undefined) {
                            let that = this; //修复监听时jquery中的this覆盖原来的对象
                            mainform.find("[name=" + i + "]")
                                .after("<span class='ckless' style=''>至少输入" + t[i] + "个，已经输入<span class='cknumber'>0</span>个</span>")
                                .data("more", t[i])
                                .bind('input propertychange', function() {
                                    let name = $(this).attr("name");
                                    let num = $(this).val().length;
                                    let number = $(this).next(".ckmore").find(".cknumber");
                                    number.html(num);
                                    if (num < $(this).data("more")) {
                                        number.css("color", "red");
                                        that.item[name].subflag = false;
                                    } else {
                                        number.css("color", "black");
                                        that.item[name].subflag = true;
                                    }
                                });
                        }
                    }
                }
                return this;
            }, //morethan

            bindUE: function(t) {
                if (arguments.length > 1) { //以参数传入
                    if (this.item[arguments[0]] == undefined) {
                        this.item[arguments[0]] = {
                            ismust: false,
                            name: arguments[0],
                            subflag: true,
                            txt: $("li:has(#" + arguments[1] + ")>label").last().text(),
                            type: $("#" + arguments[1]).prop("tagName")
                        };
                    }

                    this.item[arguments[0]]["ueditor"] = arguments[1];
                } else if (arguments.length == 0) {
                    console.error("must be an argument");
                } else { //以json传入
                    if (typeof t != "object") {
                        console.error("type error, must be like {name:'ueditorid'}");
                    } else {
                        for (let i in t) {
                            if (this.item[i] == undefined) {
                                this.item[i] = {
                                    ismust: false,
                                    name: i,
                                    subflag: true,
                                    txt: $("li:has(#" + t[i] + ")>label").last().text(),
                                    type: $("#" + t[i]).prop("tagName")
                                };
                            }
                            this.item[i].ueditor = t[i];

                        }
                    }
                }
                return this;
            }, //bindUE

            btn: mainform.find("[type=submit]"),

            init: function() {
                this.btn.attr("type", "button");
                let famm = this;
                this.additem();
                this.btn.click(function() {
                    famm.submit();
                });

                return this;
            }, //init

            additem: function() {
                let type, fitem, name, value;

                mainform.find(':input').each(function(){
                    fitem = $(this);
                    name = fitem.attr('name');
                    if(name && !formmy.item[name]){
                        formmy.item[name] = {name: name, value: fitem.attr('value')};
                        type = fitem.attr('type')?fitem.attr('type'):fitem.prop("tagName").toLowerCase();

                        formmy.item[name].txt = $("li:has([name='" + name + "'])>label").last().text();
                        formmy.item[name].type = type;
                        formmy.item[name].subflag = true;
                        formmy.item[name].ismust = false;
                    }
                });
                
                this.item = formmy.item;
                return this;

            }, //additem

            removeitem: function(s) {
                for (let i in s) {
                    try {
                        delete formmy.item[s[i]];
                    } catch (err) {
                        console.error(err);
                    }
                }

                return this;
            }, //removeitem
            item: formmy.item
        } //end prototype

    return formhelper.prototype.init();
}